package com.loe.ktui.custom

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.util.AttributeSet
import android.util.TypedValue
import android.view.*
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.res.*
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.isVisible
import com.loe.ktui.*
import com.loe.ktui.ktDp
import com.loe.ktui.setKtDelayClickListener
import com.loe.ktui.KtFrameLayout
import com.loe.ktui.UiFrameLayout
import com.loe.ktui.UiGroup
import com.loe.ktui.util.UiShape

open class UiTitleView(id: String? = null) : UiFrameLayout(id)
{
    override var width: Any? = MATCH_PARENT

    var leftVisible: Boolean? = null
    var leftSrc: Any? = null
    var leftSrcRes: Int? = null
    var leftWidth: Any? = null
    var leftLink: String? = null
    var barHeight: Any = 45
    var barVisible: Boolean? = null
    var barBg: Any? = null
    var barBgRes: Int? = null
    var titleText: CharSequence? = null
    var titleBold: Boolean? = null
    var titleSize: Any? = null
    var titleGravity: Int? = null
    var rightText: CharSequence? = null
    var rightWidth: Any? = null
    var rightSrc: Any? = null
    var rightSrcRes: Int? = null
    var rightEnable: Boolean? = null
    var rightLink: String? = null
    var color: Int? = null

    var statusFull: Boolean? = null
    var statusBgColor: Int? = null
    var statusVisible: Boolean? = null
    var captionVisible: Boolean? = null
    var navigationVisible: Boolean? = null
    var imeVisible: Boolean? = null
    var statusLight: Boolean? = false
    var navigationLight: Boolean? = null

    open var onRightClick: (View.() -> Unit)? = null
    open fun onRightClick(onRightClick: View.() -> Unit)
    {
        this.onRightClick = onRightClick
    }

    open var delayRightClick: (View.() -> Unit)? = null
    open fun delayRightClick(delayRightClick: View.() -> Unit)
    {
        this.delayRightClick = delayRightClick
    }

    fun initUI(context: Context, view: KtTitleView)
    {
        super.initUI(context, view)

        leftVisible?.let { view.leftVisible = it }
        leftSrc?.let {
            if (it is UiShape)
            {
                view.imageLeftView.setImageDrawable(it.createDrawable())
            } else
            {
                view.imageLeftView.src = it.toString()
            }
        }
        leftWidth?.let { view.leftWidth = it.dist }
        leftSrcRes?.let { view.imageLeftView.setImageResource(it) }
        view.barHeight = barHeight.dist
        barVisible?.let { view.barView.isVisible = it }
        barBg?.let {
            if (it is UiShape)
            {
                view.barView.background = it.createDrawable()
            } else if (it is Int)
            {
                view.barView.setBackgroundColor(it)
            } else
            {
                view.barView.bg = it.toString()
            }
        }
        barBgRes?.let { view.barView.setBackgroundResource(it) }
        titleText?.let { view.textTitleView.text = it }
        titleBold?.let { view.titleBold = it }
        titleSize?.let { view.titleSize = it.distFloat }
        titleGravity?.let { view.titleGravity = it }
        rightText?.let { view.rightText = it }
        rightWidth?.let { view.rightWidth = it.dist }
        rightSrc?.let {
            view.textRightView.isVisible = false
            view.imageRightView.isVisible = true
            if (it is UiShape)
            {
                view.imageRightView.setImageDrawable(it.createDrawable())
            } else
            {
                view.imageRightView.src = it.toString()
            }
        }
        rightSrcRes?.let { view.imageRightView.setImageResource(it) }
        rightEnable?.let { view.rightEnable = it }
        color?.let { view.color = it }

        statusFull?.let { view.statusFull = it }
        statusBgColor?.let { view.statusBgColor = it }
        statusVisible?.let { view.statusVisible = it }
        captionVisible?.let { view.captionVisible = it }
        navigationVisible?.let { view.navigationVisible = it }
        imeVisible?.let { view.imeVisible = it }
        statusLight?.let { view.statusLight = it }
        navigationLight?.let { view.navigationLight = it }

        leftLink?.let { view.leftLink = it }
        rightLink?.let { view.rightLink = it }
        onRightClick?.let { onClick -> view.setRightListener { view.onClick() } }
        delayRightClick?.let { delayClick -> view.setDelayRightListener { view.delayClick() } }
    }

    override fun createView(context: Context, parent: ViewGroup?): KtTitleView
    {
        return KtTitleView(context).also()
        {
            initUI(context, it)
            addToParent(parent, it)
        }
    }
}

fun Any.ui_TitleView(id: String? = null, block: (UiTitleView.() -> Unit)? = null): UiTitleView
{
    val ui = UiTitleView(id)
    block?.let { ui.it() }
    if (this is UiGroup) addChild(ui)
    return ui
}

open class KtTitleView : KtFrameLayout
{
    constructor(context: Context) : super(context)
    {
        initXML()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    {
        initXML(context.obtainStyledAttributes(attrs, R.styleable.KtTitleView))
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    {
        initXML(context.obtainStyledAttributes(attrs, R.styleable.KtTitleView, defStyleAttr, 0))
    }

    private fun initXML(typedArray: TypedArray? = null)
    {
        barView = inflate(context, R.layout.kt_title_layout, null) as FrameLayout
        addView(barView)

        imageLeftView = findViewById(R.id.imageTitleLeft)
        textTitleView = findViewById(R.id.textTitleTitle)
        textRightView = findViewById(R.id.textTitleRight)
        imageRightView = findViewById(R.id.imageTitleRight)

        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        statusHeight = resources.getDimensionPixelSize(resourceId)

        imageLeftView.setOnClickListener()
        {
            try
            {
                (context as Activity).onBackPressed()
            } catch (e: Exception)
            {
            }
        }
        barView.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom)
        setPadding(0, 0, 0, 0)

        // xml参数
        typedArray?.let()
        {
            if (it.hasValue(R.styleable.KtTitleView_kt_leftVisible))
            {
                leftVisible = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_leftVisible)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_leftSrc))
            {
                imageLeftView.setImageDrawable(it.getDrawableOrThrow(R.styleable.KtTitleView_kt_leftSrc))
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_leftLink))
            {
                leftLink = it.getStringOrThrow(R.styleable.KtTitleView_kt_leftLink)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_leftWidth))
            {
                leftWidth = it.getDimensionOrThrow(R.styleable.KtTitleView_kt_leftWidth).toInt()
            }

            barHeight = it.getDimension(R.styleable.KtTitleView_kt_barHeight, ktPx(45.0).toFloat()).toInt()

            if (it.hasValue(R.styleable.KtTitleView_kt_barVisible))
            {
                barView.isVisible = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_barVisible)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_barBg))
            {
                barView.background = it.getDrawableOrThrow(R.styleable.KtTitleView_kt_barBg)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_titleText))
            {
                titleText = it.getStringOrThrow(R.styleable.KtTitleView_kt_titleText)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_titleBold))
            {
                titleBold = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_titleBold)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_titleSize))
            {
                titleSize = it.getDimensionOrThrow(R.styleable.KtTitleView_kt_titleSize)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_titleGravity))
            {
                titleGravity = it.getIntOrThrow(R.styleable.KtTitleView_kt_titleGravity)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_rightText))
            {
                rightText = it.getStringOrThrow(R.styleable.KtTitleView_kt_rightText)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_rightWidth))
            {
                rightWidth = it.getDimensionOrThrow(R.styleable.KtTitleView_kt_rightWidth).toInt()
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_rightSrc))
            {
                textRightView.isVisible = false
                imageRightView.isVisible = true
                imageRightView.setImageDrawable(it.getDrawableOrThrow(R.styleable.KtTitleView_kt_rightSrc))
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_rightEnable))
            {
                rightEnable = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_rightEnable)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_rightLink))
            {
                rightLink = it.getStringOrThrow(R.styleable.KtTitleView_kt_rightLink)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_color))
            {
                color = it.getColorOrThrow(R.styleable.KtTitleView_kt_color)
            }

            if (it.hasValue(R.styleable.KtTitleView_kt_statusFull))
            {
                statusFull = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_statusFull)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_statusBgColor))
            {
                statusBgColor = it.getColorOrThrow(R.styleable.KtTitleView_kt_statusBgColor)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_statusVisible))
            {
                statusVisible = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_statusVisible)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_captionVisible))
            {
                captionVisible = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_captionVisible)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_navigationVisible))
            {
                navigationVisible = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_navigationVisible)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_imeVisible))
            {
                imeVisible = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_imeVisible)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_statusLight))
            {
                statusLight = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_statusLight)
            }
            if (it.hasValue(R.styleable.KtTitleView_kt_navigationLight))
            {
                navigationLight = it.getBooleanOrThrow(R.styleable.KtTitleView_kt_navigationLight)
            }

            it.recycle()
        }
    }

    lateinit var barView: FrameLayout
        internal set

    lateinit var imageLeftView: ImageView
        internal set
    lateinit var textTitleView: TextView
        internal set
    lateinit var textRightView: TextView
        internal set
    lateinit var imageRightView: ImageView
        internal set

    var statusHeight = 0
        private set

    /**
     * 设置标题栏高度
     */
    inline var barHeight: Int
        get() = barView.layoutParams.height
        set(value)
        {
            val params = barView.layoutParams
            params.height = value
            barView.layoutParams = params
        }

    /** 颜色 */
    inline var color: Int
        get() = textTitleView.currentTextColor
        set(value)
        {
            imageLeftView.setColorFilter(value)
            textTitleView.setTextColor(value)
            textRightView.setTextColor(value)
            imageRightView.setColorFilter(value)
        }

    /**
     * 标题文字
     */
    inline var titleText: CharSequence
        get() = textTitleView.text
        set(value)
        {
            textTitleView.text = value
        }

    /**
     * 标题文字粗体
     */
    inline var titleBold: Boolean
        get() = textTitleView.typeface == Typeface.DEFAULT_BOLD
        set(value)
        {
            textTitleView.typeface = if (value) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
        }

    /**
     * 标题文字大小
     */
    var titleSize: Float
        get() = ktDp(textTitleView.textSize.toDouble())
        set(value)
        {
            textTitleView.setTextSize(TypedValue.COMPLEX_UNIT_PX, value)
        }

    /**
     * 设置标题对齐方式
     */
    inline var titleGravity: Int
        get() = textTitleView.gravity
        set(value)
        {
            textTitleView.gravity = value
        }

    /**
     * 右边文字
     */
    inline var rightText: CharSequence
        get() = textRightView.text
        set(value)
        {
            textRightView.text = value
            if (value.isNotEmpty())
            {
                textRightView.isVisible = true
                imageRightView.isVisible = false
            } else
            {
                textRightView.isVisible = false
            }
        }

    inline var rightWidth: Int
        get() = imageRightView.layoutParams.width
        set(value)
        {
            val params = imageRightView.layoutParams
            params.width = value
            imageRightView.layoutParams = params
        }

    /**
     * 设置右边允许
     */
    var rightEnable: Boolean
        get() = false
        set(value)
        {
            textRightView.isEnabled = value
            textRightView.alpha = if (value) 1f else 0.65f

            imageRightView.isEnabled = value
            imageRightView.alpha = if (value) 1f else 0.65f
        }

    inline var leftWidth: Int
        get() = imageLeftView.layoutParams.width
        set(value)
        {
            val params = imageLeftView.layoutParams
            params.width = value
            imageLeftView.layoutParams = params
        }

    var leftLink = ""
        set(value)
        {
            field = value
            setDelayLeftListener { KtUi.onLink?.invoke(context, value) }
        }

    var rightLink = ""
        set(value)
        {
            field = value
            setDelayRightListener { KtUi.onLink?.invoke(context, value) }
        }

    var leftVisible = true
        set(value)
        {
            field = value
            imageLeftView.isVisible = value
        }

    /**
     * 设置右边监听
     */
    fun setRightListener(onClick: (v: View) -> Unit)
    {
        textRightView.setOnClickListener(onClick)
        imageRightView.setOnClickListener(onClick)
    }

    /**
     * 设置右边监听
     */
    fun setDelayRightListener(onClick: (v: View) -> Unit)
    {
        textRightView.setKtDelayClickListener(0, 1200, onClick)
        imageRightView.setKtDelayClickListener(0, 1200, onClick)
    }

    /**
     * 设置左边监听
     */
    fun setLeftListener(onClick: (v: View) -> Unit)
    {
        imageLeftView.setOnClickListener(onClick)
    }

    /**
     * 设置左边监听
     */
    fun setDelayLeftListener(onClick: (v: View) -> Unit)
    {
        imageLeftView.setKtDelayClickListener(0, 1200, onClick)
    }

    /*************************************************** 系统栏 ************************************************/

    val oldWindowController by lazy {
        val controller = ViewCompat.getWindowInsetsController(this)
        controller?.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        controller
    }

    val newWindowController: WindowInsetsController? by lazy {
        var controller: WindowInsetsController? = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
        {
            controller = (context as Activity).window.insetsController
            controller?.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
        controller
    }

    /** 状态栏、标题栏、导航栏 显示 */
    var systemBarsVisible: Boolean = false
        @SuppressLint("NewApi")
        set(value)
        {
            field = value
            if (oldWindowController != null)
            {
                if (value)
                {
                    oldWindowController?.show(WindowInsetsCompat.Type.systemBars())
                } else
                {
                    oldWindowController?.hide(WindowInsetsCompat.Type.systemBars())
                }
            } else
            {
                ktSafe()
                {
                    if (value)
                    {
                        newWindowController?.show(WindowInsets.Type.systemBars())
                    } else
                    {
                        newWindowController?.hide(WindowInsets.Type.systemBars())
                    }
                }
            }
        }

    /** 状态栏 背景 */
    inline var statusBgColor: Int
        get() = (context as Activity).window.statusBarColor
        set(value)
        {
            try
            {
                (context as Activity).window.statusBarColor = value
            } catch (e: Exception)
            {
            }
        }

    /** 状态栏 全屏 */
    var statusFull: Boolean = false
        set(value)
        {
            field = value
            try
            {
                val window = (context as Activity).window

                if (value)
                {
                    window.statusBarColor = Color.TRANSPARENT
                    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                    window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or SYSTEM_UI_FLAG_LAYOUT_STABLE
                } else
                {
                    window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_STABLE
                }

                // WindowCompat.setDecorFitsSystemWindows(window, !value)
                setPadding(0, if (value) statusHeight else 0, 0, 0)
            } catch (e: Exception)
            {
            }
        }

    /** 状态栏 显示 */
    var statusVisible: Boolean = false
        @SuppressLint("NewApi")
        set(value)
        {
            field = value
            if (oldWindowController != null)
            {
                if (value)
                {
                    oldWindowController?.show(WindowInsetsCompat.Type.statusBars())
                } else
                {
                    oldWindowController?.hide(WindowInsetsCompat.Type.statusBars())
                }
            } else
            {
                ktSafe()
                {
                    if (value)
                    {
                        newWindowController?.show(WindowInsets.Type.statusBars())
                    } else
                    {
                        newWindowController?.hide(WindowInsets.Type.statusBars())
                    }
                }
            }
        }

    /** 标题栏 显示 */
    var captionVisible: Boolean = false
        @SuppressLint("NewApi")
        set(value)
        {
            field = value
            if (oldWindowController != null)
            {
                if (value)
                {
                    oldWindowController?.show(WindowInsetsCompat.Type.captionBar())
                } else
                {
                    oldWindowController?.hide(WindowInsetsCompat.Type.captionBar())
                }
            } else
            {
                ktSafe()
                {
                    if (value)
                    {
                        newWindowController?.show(WindowInsets.Type.captionBar())
                    } else
                    {
                        newWindowController?.hide(WindowInsets.Type.captionBar())
                    }
                }
            }
        }

    /** 导航栏 显示 */
    var navigationVisible: Boolean = false
        @SuppressLint("NewApi")
        set(value)
        {
            field = value
            if (oldWindowController != null)
            {
                if (value)
                {
                    oldWindowController?.show(WindowInsetsCompat.Type.navigationBars())
                } else
                {
                    oldWindowController?.hide(WindowInsetsCompat.Type.navigationBars())
                }
            } else
            {
                ktSafe()
                {
                    if (value)
                    {
                        newWindowController?.show(WindowInsets.Type.navigationBars())
                    } else
                    {
                        newWindowController?.hide(WindowInsets.Type.navigationBars())
                    }
                }
            }
        }

    /** 软键盘 显示 */
    var imeVisible: Boolean = false
        @SuppressLint("NewApi")
        set(value)
        {
            field = value
            if (oldWindowController != null)
            {
                if (value)
                {
                    oldWindowController?.show(WindowInsetsCompat.Type.ime())
                } else
                {
                    oldWindowController?.hide(WindowInsetsCompat.Type.ime())
                }
            } else
            {
                ktSafe()
                {
                    if (value)
                    {
                        newWindowController?.show(WindowInsets.Type.ime())
                    } else
                    {
                        newWindowController?.hide(WindowInsets.Type.ime())
                    }
                }
            }
        }

    /** 状态字体亮色 */
    var statusLight: Boolean = false
        @SuppressLint("NewApi")
        set(value)
        {
            field = value
            if (oldWindowController != null)
            {
                oldWindowController?.isAppearanceLightStatusBars = !value
            } else
            {
                ktSafe()
                {
                    val state = if (value) 0 else WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
                    newWindowController?.setSystemBarsAppearance(state, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS)
                }
            }
        }

    /** 导航栏字体亮色 */
    var navigationLight: Boolean = false
        @SuppressLint("NewApi")
        set(value)
        {
            field = value
            if (oldWindowController != null)
            {
                oldWindowController?.isAppearanceLightNavigationBars = !value
            } else
            {
                ktSafe()
                {
                    val state = if (value) 0 else WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
                    newWindowController?.setSystemBarsAppearance(state, WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS)
                }
            }
        }
}